package com.jy.adscm.operation.mask.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jy.adscm.bean.system.JyCode;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.cg.bean.CgMaterial;
import com.jy.adscm.operation.cg.service.CgMaterialService;
import com.jy.adscm.operation.mask.bean.*;
import com.jy.adscm.operation.mask.service.*;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.support.SimpleCoreResponse;
import com.jy.adscm.system.mapper.mysql.JyCodeMapper;
import com.jy.adscm.system.service.JyUserService;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import com.jy.adscm.utils.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 口罩生产工人工作记录表 前端控制器
 * </p>
 *
 * @author yyy
 * @since 2020-03-24
 */
@RestController
@RequestMapping("/adscm/operation/mask/maskWorkRecord")
public class MaskWorkRecordController {

    @Autowired
    MaskWorkRecordService maskWorkRecordService;
    @Autowired
    MaskWorkRecordImgsService maskWorkRecordImgsService;
    @Autowired
    JyUserService jyUserService;
    @Autowired
    KzMachineService kzMachineService;
    @Autowired
    JyCodeMapper jyCodeMapper;
    @Autowired
    RedisTemplate<Object, Token> tokenRedisTemplate;
    @Autowired
    KzMaterialDetailService kzMaterialDetailService;
    @Autowired
    KzMaterialService kzMaterialService;
    @Autowired
    CgMaterialService cgMaterialService;
    @Value("${mask.print}")
    private String maskPrint;
    /**
     * 新增工作内容
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/insertRecord")
    public SimpleCoreResponse insertRecord(@RequestBody MaskWorkRecord record) throws AdscmSystemException {

        if (record.getEmpId() == null){
            throw new AdscmSystemException("员工ID为Null");
        }
        if (record.getMacCode() == null){
            throw new AdscmSystemException("机器编码为Null");
        }
        if (record.getRecordType() == null){
            throw new AdscmSystemException("记录类型为Null");
        }

        JyUser jyUser = jyUserService.selectById(record.getEmpId());
        if (jyUser == null){
            throw new AdscmSystemException("没有查询到当前的用户信息");
        }

//        List<KzMachine> machines = kzMachineService.selectByCode(record.getMacCode());

        KzMachine machine =  kzMachineService.selectById(record.getWorkMac());
        if (machine != null) {
            record.setBelongGx(machine.getBelongGx());
            record.setWorkMac(machine.getId());

            //口罩生产工序
            List<JyCode> gxList = jyCodeMapper.getJyCodeByCodeType("MASK_GX");
            for (JyCode jyCode : gxList) {
                if(jyCode.getCode().equals(record.getBelongGx())){
                    record.setBelongGxDesc(jyCode.getName());
                    break;
                }
            }
        }
        record.setRecordTime(new Date());

        //合格品输出的箱号序列号
        String printRemark = null;
        String recordType = record.getRecordType();
        if("1".equals(recordType)){
            //二维码录入
            Wrapper<KzMaterialDetail> mdWrapper = new EntityWrapper<>();
            mdWrapper.eq("code",record.getMatterCode());
            List<KzMaterialDetail> details = kzMaterialDetailService.selectList(mdWrapper);
            if (details != null && details.size()>0){
                KzMaterialDetail detail = details.get(0);
                KzMaterial material = kzMaterialService.selectById(detail.getPid());
                CgMaterial cgMaterial = cgMaterialService.selectById(material.getMaterial());

                if (detail.getWeight() != null){
                    record.setProductWeight(detail.getWeight().doubleValue());
                }
                record.setMaterialId(cgMaterial.getId().longValue());
                record.setMaterialName(cgMaterial.getName() + cgMaterial.getType());

            }

        }else if("2".equals(recordType) || "3".equals(recordType) || "4".equals(recordType)){
            //照片录入
            //看是否选择了物料类型
            Long materialId = record.getMaterialId();
            if (materialId != null && materialId > 0){
                CgMaterial cgMaterial = cgMaterialService.selectById(materialId);
                if (cgMaterial != null){
                    record.setMaterialName(cgMaterial.getName() + cgMaterial.getType());
                }
            }

        }else if ("5".equals(recordType)){
            //合格品输出
            this.temp(record,recordType);
            if(!"3".equals(machine.getBelongGx())){
                record.setBoxSerialQrCode("合格"+ machine.getName() + "-" + record.getBoxSerial());
                printRemark = jyUser.getName() + "-" +  record.getBelongGxDesc();
                HttpRequest.sendPost("http://"+maskPrint+"/javaPrint/qrCodeAndRemarkPrint","qrCode="+record.getBoxSerialQrCode() + "&remark="+printRemark);
            }
        }else if("6".equals(recordType)){
            //返工品输出
            this.temp(record,recordType);
            if(!"3".equals(machine.getBelongGx())){
                record.setBoxSerialQrCode("返工-"+ machine.getName() + "-" + record.getBoxSerial());
                printRemark = jyUser.getName() + "-" +  record.getBelongGxDesc();
                HttpRequest.sendPost("http://"+maskPrint+"/javaPrint/qrCodeAndRemarkPrint","qrCode="+record.getBoxSerialQrCode() + "&remark="+printRemark);
            }
        }
        this.temp1(record);

        return new SimpleCoreResponse("200","成功",null);
    }


    private void temp(MaskWorkRecord record,String recordType){
        Wrapper<MaskWorkRecord> rWrapper = new EntityWrapper<>();
//        rWrapper.eq("belong_gx",record.getBelongGx());
        rWrapper.eq("work_mac",record.getWorkMac());
        rWrapper.eq("record_type",recordType);
        rWrapper.orderBy("box_serial",false);
        Page<MaskWorkRecord> pp = new Page<>(0,1);
        pp = maskWorkRecordService.selectPage(pp, rWrapper);
        if (pp != null){
            List<MaskWorkRecord> ppRecords = pp.getRecords();
            if (ppRecords != null && ppRecords.size()>0){
                MaskWorkRecord maskWorkRecord = ppRecords.get(0);
                Long maxBoxSerial = maskWorkRecord.getBoxSerial();
                if (maxBoxSerial == null){
                    maxBoxSerial = 0L;
                }
                record.setBoxSerial(maxBoxSerial + 1L);
            }else {
                record.setBoxSerial(1L);
            }
        }else {
            record.setBoxSerial(1L);
        }
    }
    private void temp1(MaskWorkRecord record){
        maskWorkRecordService.insert(record);
        List<MaskWorkRecordImgs> imgs = record.getRecordImgs();
        if (imgs != null && imgs.size()>0){
            for (MaskWorkRecordImgs img : imgs) {
                img.setRecordId(record.getId());
            }
            maskWorkRecordImgsService.insertBatch(imgs);
        }

    }


    /**
     * 分页条件查询工作内容
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/selectRecordPageByCondition")
    public SimpleCoreResponse selectRecordPageByCondition(@RequestBody QueryWorkRecord record) throws AdscmSystemException {

        if (record.getCurrentPage() == null){
           record.setCurrentPage(0);
        }
        if (record.getPageSize() == null){
            record.setPageSize(10);
        }

        Page<MaskWorkRecord> page = new Page<>(record.getCurrentPage(),record.getPageSize());

        Wrapper<MaskWorkRecord> workRecordWrapper = new EntityWrapper<>();
        if(record.getEmpName() != null){
            Wrapper<JyUser> userWrapper = new EntityWrapper<>();
            userWrapper.like("name",record.getEmpName());
            List<JyUser> jyUsers = jyUserService.selectList(userWrapper);
            List<Integer> empIdList = new ArrayList<>();
            if (jyUsers != null && jyUsers.size()>0){
                for (JyUser user : jyUsers) {
                    empIdList.add(user.getId());
                }
            }else{
                empIdList.add(-9999);
            }
            workRecordWrapper.in("emp_id",empIdList);
        }
        if (record.getEmpId() != null){
            workRecordWrapper.eq("emp_id",record.getEmpId());
        }
        if (record.getRecordBeginTime() != null){
            workRecordWrapper.ge("record_time",record.getRecordBeginTime() );
        }
        if (record.getRecordEndTime() != null){
            workRecordWrapper.le("record_time",record.getRecordEndTime() );
        }
        if (record.getMatterCode() != null){
            workRecordWrapper.eq("matter_code",record.getMatterCode());
        }
        if (record.getBelongGx() != null){
            workRecordWrapper.eq("belong_gx",record.getBelongGx());
        }
        if (record.getWorkMac() != null){
            workRecordWrapper.eq("work_mac",record.getWorkMac());
        }
        if (record.getRecordType() != null){
            workRecordWrapper.eq("record_type",record.getRecordType());
        }
        workRecordWrapper.orderBy("record_time",false);

        Map<String,Object> map = new HashMap<>();

        page = maskWorkRecordService.selectPage(page,workRecordWrapper);
        int count = maskWorkRecordService.selectCount(workRecordWrapper);
        page.setTotal(count);

        //口罩生产工序
        List<JyCode> gxList = jyCodeMapper.getJyCodeByCodeType("MASK_GX");
        map.put("mask_gx",gxList);
        Map<String ,String> gxMap = new HashMap<>();
        for (JyCode jyCode : gxList) {
            gxMap.put(jyCode.getCode(),jyCode.getName());
        }
        //口罩生产记录类型
        List<JyCode> recordList = jyCodeMapper.getJyCodeByCodeType("MASK_RECORD");
        map.put("mask_record",recordList);
        Map<String ,String> recordMap = new HashMap<>();
        for (JyCode jyCode : recordList) {
            recordMap.put(jyCode.getCode(),jyCode.getName());
        }

        Wrapper<KzMachine> macWrapper = new EntityWrapper<>();
        macWrapper.eq("state" ,1);
        List<KzMachine> machines = kzMachineService.selectList(macWrapper);

        map.put("machines",machines);
        Map<Integer ,KzMachine> macMap = new HashMap<>();
        for (KzMachine mac : machines) {
            macMap.put(mac.getId(),mac);
        }

        List<MaskWorkRecord> records = page.getRecords();
        if (records != null && records.size()>0){



            for (MaskWorkRecord workRecord : records) {

                JyUser jyUser = jyUserService.selectById(workRecord.getEmpId());
                if (jyUser != null){
                    workRecord.setEmpName(jyUser.getName());
                }
                if (workRecord.getRecordTime() != null){
                    workRecord.setRecordTimeDesc(AdscmDateUtils.getDateFomat(workRecord.getRecordTime()));
                }
                if (workRecord.getBelongGx() != null){
                    workRecord.setBelongGxDesc(gxMap.get(workRecord.getBelongGx()));
                }
                if (workRecord.getWorkMac() != null){
                    workRecord.setMachine(macMap.get(workRecord.getWorkMac()));
                    workRecord.setMacName(workRecord.getMachine().getName());
                }
                if (workRecord.getRecordType() != null){
                    workRecord.setRecordTypeDesc(recordMap.get(workRecord.getRecordType()));
                }
                if (workRecord.getMatterCode() == null){
                    workRecord.setMatterCode("-");
                }

                Wrapper<MaskWorkRecordImgs> recordImgsWrapper = new EntityWrapper<>();
                recordImgsWrapper.eq("record_id",workRecord.getId());
                List<MaskWorkRecordImgs> imgs = maskWorkRecordImgsService.selectList(recordImgsWrapper);
                workRecord.setRecordImgs(imgs);
            }
        }

        map.put("page",page);
        return new SimpleCoreResponse("200","查询成功",map);
    }

    /**
     * 远程调用打印合格品、返工品二维码服务
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/printWorkQrCode/{recordId}")
    public SimpleCoreResponse printWorkQrCode(@PathVariable("recordId")String recordId) throws AdscmSystemException {

        MaskWorkRecord record = maskWorkRecordService.selectById(recordId);


        JyUser jyUser = jyUserService.selectById(record.getEmpId());
        if (jyUser == null){
            throw new AdscmSystemException("没有查询到当前的用户信息");
        }

        KzMachine machine = kzMachineService.selectById(record.getWorkMac());
        if (machine != null) {
            record.setBelongGx(machine.getBelongGx());
            record.setWorkMac(machine.getId());

            //口罩生产工序
            List<JyCode> gxList = jyCodeMapper.getJyCodeByCodeType("MASK_GX");
            for (JyCode jyCode : gxList) {
                if(jyCode.getCode().equals(record.getBelongGx())){
                    record.setBelongGxDesc(jyCode.getName());
                    break;
                }
            }
        }
        //合格品输出的箱号序列号
        String printRemark = null;
        String recordType = record.getRecordType();
        if (record.getBoxSerial() != null && machine != null){
            if ("5".equals(recordType)){
                //合格品输出
//                printRemark = jyUser.getName() + "-" +  machine.getName() + "合格品";
                printRemark = jyUser.getName() + "-" +  record.getBelongGxDesc();
                String param = "qrCode="+record.getBoxSerialQrCode() + "&remark="+printRemark;
                System.out.println("合格品输出："+param);
                HttpRequest.sendPost("http://"+maskPrint+"/javaPrint/qrCodeAndRemarkPrint",param);
            }else if("6".equals(recordType)){
                //返工品输出
//                printRemark = jyUser.getName() + "-" +  machine.getName() + "返工品";
                printRemark = jyUser.getName() + "-" +  record.getBelongGxDesc();
                String param = "qrCode="+record.getBoxSerialQrCode() + "&remark="+printRemark;
                System.out.println("返工品输出："+param);
                HttpRequest.sendPost("http://"+maskPrint+"/javaPrint/qrCodeAndRemarkPrint",param);
            }
        }else {
            System.out.println("record.getBoxSerial():"+record.getBoxSerial());
            System.out.println("machine:"+machine);
            throw new AdscmSystemException("调用打印机异常...");
        }


        return new SimpleCoreResponse("200","成功",null);
    }


    /**
     * 工序统计报表
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/gxReportForm")
    public SimpleCoreResponse gxReportForm(@RequestParam("beginTime")String beginTime,@RequestParam("endTime")String endTime) throws AdscmSystemException {

        return new SimpleCoreResponse("200","成功",maskWorkRecordService.gxReportForm(beginTime,endTime));
    }
    /**
     * 工序统计甘特图
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/gxReportGantt")
    public SimpleCoreResponse gxReportGantt(@RequestParam("macId")Long macId,@RequestParam("beginTime")String beginTime,@RequestParam("endTime")String endTime) throws AdscmSystemException {

        return new SimpleCoreResponse("200","成功",maskWorkRecordService.gxReportGantt(macId,beginTime,endTime));
    }

    /**
     * 修改工作记录
     * @param maskWorkRecord
     * @param request
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/update")
    public SimpleCoreResponse update(@RequestBody MaskWorkRecord maskWorkRecord , HttpServletRequest request) throws AdscmSystemException {
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        Boolean result=  maskWorkRecordService.updateMaskWorkRecord(maskWorkRecord, token);
        return new SimpleCoreResponse("200","成功",result);
    }

    /**
     * 逻辑删除该数据
     * @param id
     * @param request
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/deleteById/{id}")
    public SimpleCoreResponse deleteById(@PathVariable  Long id , HttpServletRequest request) throws AdscmSystemException {
        String tokenId = request.getParameter("tokenId");
        Token token = AdscmBaseUtils.getInstance().getTokenByTokenId(tokenId, tokenRedisTemplate);
        Boolean result=  maskWorkRecordService.deleteMaskWorkRecord(id, token);
        return new SimpleCoreResponse("200","成功",result);
    }


    /**
     * 工序统计柱形图，按照某一年的季度/月统计
     * @param year
     * @param type
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/gxReportBarCharts")
    public SimpleCoreResponse gxReportBarCharts(@RequestParam("year")Integer year,@RequestParam("type")Integer type) throws AdscmSystemException {

        return new SimpleCoreResponse("200","成功",maskWorkRecordService.gxReportBarCharts(year,type));
    }

    /**
     * 工序统计柱形图，按照周统计（如果type == 2 ，则看 year年target月所在的这几周的统计报表，否则就是year年target季度所在的这几周的统计报表）
     * @param year 年
     * @param type 1：季度，2：月
     * @param target 具体数值
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/gxReportBarChartsByWeek")
    public SimpleCoreResponse gxReportBarChartsByWeek(@RequestParam("year")Integer year,@RequestParam("type")Integer type,@RequestParam("target")Integer target) throws AdscmSystemException {

        return new SimpleCoreResponse("200","成功",maskWorkRecordService.gxReportBarChartsByWeek(year,type,target));
    }
    /**
     * 工序统计柱形图，按照班次统计某一周的统计图
     * @param year 年
     * @param week 周
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/gxReportBarChartsByClasses")
    public SimpleCoreResponse gxReportBarChartsByClasses(@RequestParam("year")Integer year,@RequestParam("week")Integer week) throws AdscmSystemException {

        return new SimpleCoreResponse("200","成功",maskWorkRecordService.gxReportBarChartsByClasses(year,week));
    }

}

